import React, { Suspense } from "react"

import { Navigate, useLocation } from "react-router-dom"
import userInfoStore from "@/store/userInfo/index"

const withAuth = (Component) => {
  const AuthenticatedComponent = (props) => {
    const { getToken } = userInfoStore()
    const location = useLocation()

    // 用户未登录，试图访问需要登录的页面
    if (!getToken() && location.pathname !== "/login") {
      return <Navigate to="/login" state={{ from: location }} replace />
    }

    // 用户登录后，试图访问登录页面
    if (getToken() && location.pathname === "/login") {
      return <Navigate to={location.state?.from?.pathname || "/"} replace />
    }

    // 所有其他情况，渲染组件
    return <Component {...props} />
  }

  return AuthenticatedComponent
}

const asyncComponentLoading = (frc) => <Suspense fallback={<></>}>{frc}</Suspense>

export { withAuth, asyncComponentLoading }
